import {defineStore} from 'pinia'
import { getCityLocate, getCityList } from '@/api/modules/city'
import type { City } from '@/api/interface'


export const useCityStore = defineStore('city',{
    state() {
        return {
          city: null as City.Item | null, // 当前选择的城市
          cities: [] as City.Item[] // 城市列表数据
        }
      },

    getters: {
        curCity
        hotCityList({ cities }) {
            return cities.filter((item) => item.isHot === 1)
          },
        cityGroup({ cities }){
            const result: City.Group[] = []

            cities.forEach((city) => {
                const py = city.pinyin.charAt(0).toUpperCase()
                const index = result.findIndex((group) => group.title === py)
                if (index > -1) {
                  // 存在，则将当前 city 追加对应 group 中
                  result[index].list.push(city)
                } else {
                  // 不存在，则主动构造一个 group 追加到 result 中
                  result.push({
                    title: py,
                    list: [city]
                  })
                }
              })
              return result.sort((a, b) => (a.title > b.title ? 1 : -1))
        },

        indexList(state) {
            return (<any>state).cityGroup.map((item: any) => item.title)
          }
        
    },

    actions:{       
        setCity(payload: City.Item) {
            this.city = payload
        },
        async getCity() {
            const { city } = await getCityLocate()
            this.city = city
          },
          async getCities() {
            const { cities } = await getCityList()
            this.cities = cities
          }
    }
})